<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\user_center\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

/**
 * 会员管理 控制器
 * @package app\user\admin
 */
class Index extends Admin
{
	
    /**
     * 用户首页
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取排序
        $order = $this->getOrder();
        // 获取筛选
        $map = $this->getMap();

        // 数据列表
        $data_list = model('Member', 'model\user')->where($map)->order($order)->paginate();

        $rel_list = [];
        foreach ($data_list as $key => $value) {
            $rel_list[$key] = $value;
            $rel_list[$key]['mobile'] = $value['get_uc_member_mobile']['mobile'];
            $rel_list[$key]['is_bindwx'] = isset($value['get_uc_member_wechat']) ? 1 : 0;
        }
		
		// 详情
        $btn_details = [
            'title' => '用户详情',
            'icon'  => 'fa fa-fw fa-bookmark',
            'href'  => url('details', ['uid' => '__uid__']),
        ];
		
        //dump($rel_list);die();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('用户管理') // 设置页面标题
            ->setPrimaryKey('uid') // 设置主键名为username
            ->setTableName('uc_member') // 设置数据表名
            //->setSearch(['id' => 'ID', 'username' => '用户名', 'email' => '邮箱']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['__INDEX__', '序号'],
                ['uid', 'UID'],
                ['avatar_url', '头像', 'img_url'],
                ['nick_name', '昵称', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['mobile', '手机绑定'],
                ['is_bindwx', '绑定微信', 'yesno'],
                ['create_time', '创建时间', 'datetime'],
                //['last_login_time', '最后登录时间', 'datetime'],
                //['last_login_ip', '最后登录IP'],
                ['member_status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
            ->setSearchArea([
                ['text', 'uid', '用户UID'],
                ['text', 'nick_name', '用户昵称', 'like'],
                ['daterange', 'create_time', '创建时间'],
                ['text', 'f_uid', '邀请人uid'],
            ])
            //->addFilter(['nick_name']) // 添加筛选
            //->addTimeFilter('create_time', '', ['开始时间', '结束时间'])
            ->addOrder('uid,create_time') // 添加排序
            //->addFilter(['is_bindwx']) // 添加筛选
            ->addTopButtons('enable,disable') // 批量添加顶部按钮
            ->addRightButton('edit') // 批量添加右侧按钮
            ->addRightButton('custom', $btn_details, ['area' => ['50%', '80%']]) // 添加授权按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 新增
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'User');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            // 非超级管理需要验证可选择角色
            if (session('user_auth.role') != 1) {
                if ($data['role'] == session('user_auth.role')) {
                    $this->error('禁止创建与当前角色同级的用户');
                }
                $role_list = RoleModel::getChildsId(session('user_auth.role'));
                if (!in_array($data['role'], $role_list)) {
                    $this->error('权限不足，禁止创建非法角色的用户');
                }
            }

            if ($user = UserModel::create($data)) {
                Hook::listen('user_add', $user);
                // 记录行为
                action_log('user_add', 'admin_user', $user['id'], UID);
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }

        // 角色列表
        if (session('user_auth.role') != 1) {
            $role_list = RoleModel::getTree(null, false, session('user_auth.role'));
        } else {
            $role_list = RoleModel::getTree(null, false);
        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'username', '用户名', '必填，可由英文字母、数字组成'],
                ['text', 'nickname', '昵称', '可以是中文'],
                ['select', 'role', '角色', '非超级管理员，禁止创建与当前角色同级的用户', $role_list],
                ['text', 'email', '邮箱', ''],
                ['password', 'password', '密码', '必填，6-20位'],
                ['text', 'mobile', '手机号'],
                ['image', 'avatar', '头像'],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1]
            ])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 用户id
     * @author jason wang <120907037@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id = null)
    {   
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            //数据验证
            $Validate = validate('Member', 'validate\member');
            if( !$Validate -> scene('edit_profile_admin') -> check($params) ){
                $this->error($Validate -> getError());
            }

            $uid    		= intval(isset($params["uid"]) ? $params["uid"] : 0);
            $nick_name  	= isset($params["nick_name"]) ? $params["nick_name"] : '';
            $sex 			= intval(isset($params["sex"]) ? $params["sex"] : 0);
            $birthday 		= isset($params["birthday"]) ? $params["birthday"] : '';
            $autograph 		= isset($params["autograph"]) ? $params["autograph"] : '';
            $attch_id 	= isset($params["avatar_url"]) ? $params["avatar_url"] : '';
            $title 	        = isset($params["title"]) ? $params["title"] : '';
            $member_status 	= isset($params["member_status"]) ? $params["member_status"] : 0;

            $avatar_url_rel = '';
            if($attch_id > 0){
                //获取本地路径
                $avatar_url = model('admin/Attachment') -> getFilePath($attch_id, 1);
                //上传OSS 
                $rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, get_avatar_user_path($uid));
                if($rel['code'] != 200) $this->error('头像上传失败');
                $avatar_url_rel = $rel['data']['info']['url'];
            }
            

            $rel = model('Member', 'model\user') -> updateDataByUser($uid, $nick_name, $sex, $autograph, $avatar_url_rel, $birthday, $member_status, $title);
            if ($rel['code'] > 0) {
                //删除本地附件
                if($attch_id > 0) controller('common/Attachmentlogic', 'logic') -> delete($attch_id);
                //$user = UserModel::get($data['id']);
                //Hook::listen('user_edit', $user);
                // 记录行为
                //action_log('user_edit', 'admin_user', $user['id'], UID, get_nickname($user['id']));
                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = model('Member', 'model\user')->find($id);

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'uid'],
                //['static', 'username', '用户名', '不可更改'],
                ['text', 'nick_name', '昵称', '可以是中文'],
                ['jcrop_oss', 'avatar_url', '头像', '', '', ['setSelect' => [0, 0, 500, 500], 'aspectRatio'=>1, 'saveWidth' => 500, 'saveHeight' => 500]],
                ['text', 'title', '头衔', '头衔'],
                //['select', 'role', '角色', '非超级管理员，禁止创建与当前角色同级的用户', $role_list],
                ['radio', 'sex', '性别', '', ['保密', '男', '女']],
                ['textarea', 'autograph',  '个性签名', '6-20位'],
                ['datetime', 'birthday', '出生年月', '', '', 'YYYY-MM-DD'],
                ['radio', 'member_status', '状态', '', ['禁用', '启用']]
            ])
            ->setFormData($info) // 设置表单数据
            //->isAjax(false)
            ->fetch();
    }

    /**
     * 启用用户
     * @param array $ids 用户id
     * @author jason wang <120907037@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($ids = [])
    {
        $rel = model('Member', 'model\user') -> where('uid', 'in', $ids)  -> setField('member_status', 1);
        if($rel){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 禁用用户
     * @param array $ids 用户id
     * @author jason wang <120907037@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($ids = [])
    {
        $rel = model('Member', 'model\user') -> where('uid', 'in', $ids)  -> setField('member_status', 0);
        if($rel){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
	
	/**
     * 详情
     * @param array $ids 用户id
     * @author shiqiang
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
	public function details($uid = []){
		$result = model('Member', 'model\user') -> getUserinfoByUseruid($uid);
		
		$status = [0=>'不显示',1=>'男',2=>'女'];
		$status2 = [1=>'手机登录',2=>'微信登陆',3=>'一键登录'];
		
		$result = $result['data'];
		$res = [];
		$res['userId'] 			= (int)$result -> uid;
		
		$res['avatorUrl'] 		= (string)get_avatar_user($result -> uid);
		$res['nickName'] 		= (string)$result -> nick_name;
		$res['sex'] 			= (string)$status[$result -> sex];
		$res['birthday'] 		= (string)substr($result -> birthday, 0, 10);
		$res['autograph'] 		= (string)$result -> autograph;
		
		//登录信息
		$res['createTime'] 			= (string)date('Y-m-d H:i:s', $result -> create_time);
		$res['lastLoginTime'] 		= (string)date('Y-m-d H:i:s', $result -> last_login_time);
		$res['lastLoginIp'] 		= (string)$result -> last_login_ip;
		$res['lastLoginType'] 		= $result -> last_login_type> 0 ? $status2[$result -> last_login_type] : '暂无';
		$res['f_uid'] 				= $result -> f_uid == '' ? '无' : $result -> f_uid;
        
        //邀请会员数
        $map = [];
        $map['f_uid'] = $uid;
        $yaoqingNum = model('Member', 'model\user') -> where($map) -> count();
		$res['loginTimes'] 		= (int)$result -> get_uc_member_count -> login_times;
		$res['friendTimes'] 	= (int)$result -> get_uc_member_count -> friend_times;
		$res['fansTimes'] 		= (int)$result -> get_uc_member_count -> fans_times;
		$res['worksTimes'] 		= (int)$result -> get_uc_member_count -> works_times;
		$res['followTimes'] 	= (int)$result -> get_uc_member_count -> follow_times;
		$res['bePraisedTimes'] 	= (int)$result -> get_uc_member_count -> be_praised_times;
		$res['praisedTimes'] 	= (int)$result -> get_uc_member_count -> praised_times;
		$res['commentTimes'] 	= (int)$result -> get_uc_member_count -> comment_times;
        $res['hotNum'] 			= (int)$result -> get_uc_member_count -> hot_num;
        $res['yaoqingNum'] 	    = (int)$yaoqingNum;//邀请会员数
		
		$this->assign('userInfo', $res);
		return $this->fetch();
	}
	
	
	/**
     * 我关注的用户列表
     * @param array $ids 用户id
     * @author shiqiang
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
	public function follow_list($uid = []){
		// 获取排序
        $order = $this->getOrder();
        // 获取筛选
        $map = $this->getMap();
        $result = model('UcMemberFollow', 'model\user') -> getListFollowByUid($uid , $map, $order);
		$result = $result['data'];
		foreach($result as $key => $value){
			$result[$key]['other'] = $value['other'] > 0 ? 1:0;
		}
		
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('用户管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为username
            ->setTableName('uc_member_follow') // 设置数据表名
			->setSearch(['a.follow_uid' => 'UID', 'b.nick_name' => '用户名']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['uid', 'UID'],
                ['nick_name', '昵称'],
                ['sex', '性别' ,['不显示','男','女']],
                ['member_status', '用户状态', 'yesno'],
				['other', '是否互关', 'yesno'],
                ['create_time', '关注时间', 'datetime'],
            ])
            ->addFilter(['nick_name']) // 添加筛选
            ->addTimeFilter('a.create_time', '', ['开始时间', '结束时间'])
            ->addOrder('a.create_time') // 添加排序
            ->setRowList($result) // 设置表格数据
            ->fetch(); // 渲染页面
	}
	
	/**
     * 我的粉丝列表
     * @param array $ids 用户id
     * @author shiqiang
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
	public function fans_list($uid = []){
		// 获取排序
        $order = $this->getOrder();
        // 获取筛选
        $map = $this->getMap();
        $result = model('UcMemberFollow', 'model\user') -> getListFansByUid($uid , $map, $order);
		$result = $result['data'];
		foreach($result as $key => $value){
			$result[$key]['other'] = $value['other'] > 0 ? 1:0;
		}
		
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('用户管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为username
            ->setTableName('uc_member_follow') // 设置数据表名
			->setSearch(['a.uid' => 'UID', 'b.nick_name' => '用户名']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['uid', 'UID'],
                ['nick_name', '昵称'],
                ['sex', '性别' ,['不显示','男','女']],
                ['member_status', '用户状态', 'yesno'],
				['other', '是否互关', 'yesno'],
                ['create_time', '关注时间', 'datetime'],
            ])
            ->addFilter(['nick_name']) // 添加筛选
            ->addTimeFilter('a.create_time', '', ['开始时间', '结束时间'])
            ->addOrder('a.create_time') // 添加排序
            ->setRowList($result) // 设置表格数据
            ->fetch(); // 渲染页面
	}
}
